$().ready(function() {

function ap_trade_buy (type, qty) {
  var data = {'buy': type};
  data[type+'qty'] = qty;
  
  if (!confirm('Do you really want buy '+ qty +' '+ type.toUpperCase() + '?')) {
    return;
  }
  
  $.post('/0/Trade/submit.php', data, function(data, textStatus) {
    if (textStatus == 'success') { alert('Bought!'); }
    else { alert('Hmmm some error!'); }
    
    window.location = '/0/Trade/';
  });
}

$.get('/0/Trade/Buy.php', function (data, textStatus) { 

  var su = $('input[name=suqty]', data).val();
  var pro = $('input[name=proqty]', data).val();
  
  // Production points
  if (pro != '0') {
    $('#awplus_content table:eq(1) tr:eq(1) td:eq(0)')
      .prepend('<div style="float: right">(<a id="ap_buy_pro" href="javascript: void(0);" title="Click to buy">'+pro+'</a>) </div>');
    
    $('#ap_buy_pro').click(function() {
      ap_trade_buy('pro', pro);
    });
  }
  
  // Suply Units
  if (su != '0') {
    $('#awplus_content table:eq(1) tr:eq(2) td:eq(0)')
      .prepend('<div style="float: right">(<a id="ap_buy_su" href="javascript: void(0);" title="Click to buy">'+su+'</a>) </div>');

    $('#ap_buy_su').click(function() {
      ap_trade_buy('su', pro);
    });
  }

});


// Sell All SU's

var tt_su = $.trim($('#awplus_content table:eq(2) tr:eq(2) td:eq(1)').text()).replace(/([0-9]+)\/.*/, '$1');

if (tt_su != '0') {
  $('#awplus_content table:eq(2) tr:eq(2) td:eq(0)')
    .prepend('<div style="float: right">(<a id="ap_sell_su" href="javascript: void(0);" title="Click to sell">Sell <strong>all</strong> SU</a>) </div>');
  
  $('#ap_sell_su')
    .data('tt_su', tt_su)
    .click(function() {
    
      if (!confirm('Do you really want sell '+ $(this).data('tt_su') +' Suply Units?')) {
        return;
      }
      
      var params = {'buy': 'su', 'suqty': $(this).data('tt_su')};
      
      $.post('/0/Trade/submit2.php', params, function(data, textStatus) {
        if (textStatus == 'success') { alert('Sold!'); }
        else { alert('Hmmm some error!'); }
        
        window.location = '/0/Trade/';
      });
    });
}

});
